﻿using Common;
using DAL.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
namespace GenCodeTask
{
    public class GenCodeBiz
    {

        /// <summary>
        /// 获取生码任务
        /// </summary>
        /// <returns></returns>
        public Queue<string> GetGenCodeTask()
        {

            Queue<string> queue = new Queue<string>();
//            string sql = @"
//                            select G.ID,G.CodeType,G.CodeTypeText,G.EnterpriseId,G.EnterpriseCode,G.Gen_Code_Nums,G.RankNum,G.VertialNum,
//                         B.Batch,G.Anti_Fake_Num,G.ActiveType,G.DisableTime,
//                        G.Logistics_Num from 
//                        CodeManage_GenCode as G INNER JOIN CodeManage_GenCodeBatch as B
//                         on G.PatchId = B.ID and G.Status = 0";
            string sql = @"
                            select G.ID,G.CodeType,G.CodeTypeText,G.EnterpriseId,G.Gen_Code_Nums,G.RankNum,G.VertialNum,
                         B.Batch,G.Anti_Fake_Num,G.ActiveType,G.DisableTime,oe.Code,
                        G.Logistics_Num from 
                        CodeManage_GenCode as G left JOIN CodeManage_GenCodeBatch as B
                         on G.PatchId = B.ID 
                         left join Organization_Enterprise oe on
                         oe.ID=G.EnterpriseId
                         where G.Status = 0";
            DataTable genCodeTable = DbHelperSQL.GetTable(sql);
            // GetImportCodeTask();
            if (genCodeTable.Rows.Count > 0)
            {
                for (int i = 0; i < genCodeTable.Rows.Count; i++)
                {
                    queue.Enqueue(genCodeTable.Rows[i]["ID"] + "-" + genCodeTable.Rows[i]["CodeType"] + "-" + genCodeTable.Rows[i]["EnterpriseId"] + "-" + genCodeTable.Rows[i]["Gen_Code_Nums"] + "-" + genCodeTable.Rows[i]["Batch"] + "-" + genCodeTable.Rows[i]["Anti_Fake_Num"] + "-" + genCodeTable.Rows[i]["Logistics_Num"] + "-" + genCodeTable.Rows[i]["RankNum"] + "-" + genCodeTable.Rows[i]["VertialNum"] + "-" + genCodeTable.Rows[i]["ActiveType"] + "-" + genCodeTable.Rows[i]["DisableTime"] + "-" + genCodeTable.Rows[i]["Code"]);
                }
                return queue;
            }
            return new Queue<string>();
        }


        /// <summary>
        /// 生码
        /// </summary>
        /// <param name="flag">生码类型</param>
        /// <param name="length">码长度</param>
        /// <param name="sum">码数量</param>
        /// <param name="companyCodeBatch">企业编码加批次</param>
        /// <param name="companyId">企业ID</param>
        /// <returns></returns>
        public bool CreateCode(string flag, int fwlength, int wllength, int sum, string companyCodeBatch, int companyId, int rankNum, int VertialNum,int ActiveType,DateTime DisableTime)
        {
            //横排 * 竖排 得到每版(每张)多少个码  即码段信息
            int codeNumB = rankNum * VertialNum;

            int BFlag =0;//标记板数 即第几版(第几张)
            string filePath = AppConst.Path + companyCodeBatch + AppConst.TxtSuffix;
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            StringBuilder strTemp = new StringBuilder();//标记最后需要打印的字符串
            DataTable tblDB = new DataTable();//将生成的防伪码和管理码放在此 用于导入数据库
            tblDB.Columns.Add("Fw_Code", typeof(string));
            tblDB.Columns.Add("Fw_CodeSecret", typeof(string));
            tblDB.Columns.Add("Wl_Code", typeof(string));
            tblDB.Columns.Add("EnterpriseId", typeof(Int32));
            tblDB.Columns.Add("CodeType", typeof(string));
            tblDB.Columns.Add("ActiveType",typeof(Int32));
            tblDB.Columns.Add("DisableTime", typeof(DateTime));
             tblDB.Columns.Add("BS",typeof(Int32));
            int num = fwlength - 6;
            string[] flags = flag.TrimEnd(',').Split(',');
            string fw_code = string.Empty;
            string wl_code = string.Empty;
            string jf_code = string.Empty;
            string resultCode = string.Empty;
            
            for (int i = sum; i > 0; i--)
            {
                
                resultCode = string.Empty;
                fw_code = CleanInput(Guid.NewGuid().ToString("N"));
                if (fw_code.Length > num)
                {
                    fw_code = fw_code.Substring(0, num);
                    fw_code = companyCodeBatch + fw_code;
                }
                else
                {
                    int num3 = num - fw_code.Length;
                    for (int j = 0; j < num3; j++)
                    {
                        fw_code = "0" + fw_code;
                    }
                    fw_code = companyCodeBatch + fw_code;
                }

                if(i%codeNumB==0){
                    BFlag++;
                }


                if (flags.Contains("1"))//包含防伪码
                    resultCode += fw_code + "-";
                if (flags.Contains("2"))//包含管理码
                {
                    wl_code = fw_code.Substring(0, wllength);
                    resultCode += wl_code + "-";
                }
                //if (flags.Contains("3"))//包含积分码(由于未确定积分码生码规则暂不实现)
                //{
                //    resultCode += fw_code;

                //}
                 
                resultCode += companyId + "-" + flag;
                sw.WriteLine(resultCode);
                

               
                DataRow dr1 = tblDB.NewRow();
                dr1["Fw_Code"] = fw_code;
                dr1["Fw_CodeSecret"] = MiMa.Jiami(fw_code, AppConst.DigitCodeKey);
                dr1["Wl_Code"] = wl_code;
                dr1["EnterpriseId"] = companyId;
                dr1["CodeType"] = flag;
                dr1["ActiveType"]=ActiveType;
                dr1["DisableTime"]=DisableTime;
                dr1["BS"]=BFlag;
                tblDB.Rows.Add(dr1);
            }
            sw.Close();
            GC.Collect();
            //创建AntiFake_Digitcode表
            try
            {
                string tableName = AppConst.TablePrefix + companyCodeBatch;
                string CodeStr = string.Empty;//标记生成的字段Code(i)的字符
                
                string createSql = string.Format(@"
                 if object_id(N'{2}',N'U') is not null
                    drop table {0}
                    create table {1}
                    (
                        ID      int     identity(1,1) primary key,
                        Fw_Code  nvarchar(100)  null,
                        Fw_CodeSecret nvarchar(100)  null,
                        Wl_Code  nvarchar(100)      null,
                        WB_Fw_Code     nvarchar(100)     null,
                        WB_Wl_Code  nvarchar(100)   null,
                        EnterpriseId  int     not null,
                        ZEnterpriseId   int  null,
                       
                       Stats   int  null,
                       QueryCount  int  null,
                       QueryTime datetime  null,
                       CreateDate datetime  null,
                       ChangeDate datetime  null,
                        ActiveType  int null,
                        DisableTime datetime  null,
                        BS    int null,
                       CodeType  nvarchar(100)  not null,
                      TempletId  int null
                    )
                --创建临时表
                if object_id(N'Tmp',N'U') is not null
                drop table Tmp   
                 create table Tmp 
                 (
                     ID   int IDENTITY (1,1)   primary key,
                     Fw_Code    nvarchar(100)     not null, 
                     Fw_CodeSecret nvarchar(100)     not null,
                     Wl_Code       nvarchar(100)     not null,
                     EnterpriseId  int not null,
                    CodeType  nvarchar(100)     not null
                 )
                    ", tableName, tableName, tableName, CodeStr);
                DbHelperSQL.ExecuteSql(createSql);
                
                DataTableToSQLServer(tblDB, companyCodeBatch);
                FileOperation.DropToFile(filePath);
                return true;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                GC.Collect();
            }

        }

        public static void DataTableToSQLServer(DataTable dt, string companyCodeBatch)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;

            using (SqlConnection destinationConnection = new SqlConnection(connectionString))
            {
                destinationConnection.Open();

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
                {
                    try
                    {

                        bulkCopy.DestinationTableName = AppConst.TablePrefix + companyCodeBatch;//要插入的表的表名
                        bulkCopy.BatchSize = dt.Rows.Count;
                        bulkCopy.ColumnMappings.Add("Fw_Code", "Fw_Code");//映射字段名 DataTable列名 ,数据库 对应的列名  
                        bulkCopy.ColumnMappings.Add("Fw_CodeSecret", "Fw_CodeSecret");
                        bulkCopy.ColumnMappings.Add("Wl_Code", "Wl_Code");
                        bulkCopy.ColumnMappings.Add("EnterpriseId", "EnterpriseId");//映射字段名 DataTable列名 ,数据库 对应的列名  
                        bulkCopy.ColumnMappings.Add("CodeType", "CodeType");
                   
                        bulkCopy.ColumnMappings.Add("ActiveType", "ActiveType");
                        bulkCopy.ColumnMappings.Add("DisableTime", "DisableTime");
                        bulkCopy.ColumnMappings.Add("BS", "BS");
                         
                        bulkCopy.WriteToServer(dt);

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {


                    }
                }


            }

        }
      
        /// <summary>
        /// 替换GUID中的字母
        /// </summary>
        /// <param name="strIn"></param>
        /// <returns></returns>
        private static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn, "[^\\d]", "");
        }

        /// <summary>
        /// 生码完成后 修改生码状态
        /// </summary>
        /// <param name="genCodeTaskId"></param>
        public void UpdateGenCodeTaskState(int genCodeTaskId)
        {
            string updateSql = string.Format("update CodeManage_GenCode set Status =1 where  ID={0}", genCodeTaskId);
            DbHelperSQL.ExecuteSql(updateSql);
        }
    }
}
